package com.app.controller;

import com.app.common.SystemConstant;
import com.app.service.AdminUserService;
import com.app.service.AttService;
import com.app.service.DepartmentService;
import com.app.service.UserService;
import com.app.model.*;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotEmpty;
import java.io.*;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.UUID;

@Controller
@RestController
@RequestMapping("/api")
public class UploadController {

    @Autowired
    AttService attService;
    @Autowired
    UserService userService;
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private DepartmentService departmentService;


    /**
     * 上传文件
     */
    @PostMapping("/upload")
    public Result<Object> upload(
            HttpServletRequest request
    ) throws IOException {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String uid = TokenUtils.verify(token);
        if (uid.equals("false")) {
            return Result.error(405, "token已过期");
        }
        UserModel userModel = userService.getUserById(Integer.parseInt(uid));
        if (userModel == null) {
            return Result.error(406, "用户不存在");
        }
        MultipartHttpServletRequest params = ((MultipartHttpServletRequest) request);
        // 获取文件
        List<MultipartFile> file = ((MultipartHttpServletRequest) request).getFiles("multipart");
        String modelName = params.getParameter("modelName");

//        Integer pid = Integer.valueOf(params.getParameter("pid"));
        String[] url = new String[file.size()];
        if (!file.isEmpty()) {
            //上传文件路径
            String path = "";
            path = SystemConstant.DEFAULT_UPLOAD_URL;
            //获得上传文件名
            for (int i1 = 0; i1 < file.size(); i1++) {
                String fileName = file.get(i1).getOriginalFilename();
                int lastIndexOf = fileName.lastIndexOf(".");
                UUID uuid = UUID.randomUUID();
//            String date = getRandomString2(8);
                //获取文件的后缀名 .jpg
                String suffix = fileName.substring(lastIndexOf);
                String suffix2 = fileName.substring(lastIndexOf + 1);

                File filePath = new File(path + File.separator + uuid + suffix);
                System.out.println(filePath);
                //如果文件目录不存在，创建目录
                if (!filePath.getParentFile().exists()) {
                    filePath.getParentFile().mkdirs();
                }
                //获取文件大小
                //将上传文件保存到一个目标文件中
                file.get(0).transferTo(filePath);
                String fileLength = String.valueOf(filePath.length());
                if (Integer.parseInt(fileLength) > 104857600) {
                    return Result.error(500, "文件过大，请注意大小");
                }
                String fileURL = "";
                fileURL = SystemConstant.DEFAULT_PDF_SERVICE_URL + uuid + suffix;
                AttModel attModel = new AttModel();
                attModel.setName(fileName);
                attModel.setAttUrl(fileURL);
                attModel.setUserId(userModel.getId());
//            attModel.setFormId();
                attModel.setAttType(suffix2);//文件大小
                attModel.setSize(fileLength);//文件后缀名
                String[] suffixType1Arr = SystemConstant.DEFAULT_type1.split(",");
                for (int i = 0; i < suffixType1Arr.length; i++) {
                    if (suffix2.contains(suffixType1Arr[i])) {
                        attModel.setType(1);
                    }
                }
                String[] suffixType2Arr = SystemConstant.DEFAULT_type2.split(",");
                for (int i = 0; i < suffixType2Arr.length; i++) {
                    if (suffix2.contains(suffixType2Arr[i])) {
                        attModel.setType(2);
                    }
                }
                String[] suffixType3Arr = SystemConstant.DEFAULT_type3.split(",");
                for (int i = 0; i < suffixType3Arr.length; i++) {
                    if (suffix2.contains(suffixType3Arr[i])) {
                        attModel.setType(3);
                    }
                }
                try {
//                model.setPid(pid);
                    attModel.setCrtTime(CommonHelp.getNowTimestamp());
                    attService.insert(attModel);
                } catch (Exception e) {
                    System.out.println(e);
                }
                url[i1] = fileURL;
            }
            return Result.success(url);
        }
        return null;
    }

    /**
     * 上传文件
     */
    @PostMapping("/admin/upload")
    public Result<String> upload2(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws
            IOException {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.valueOf(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        // 获取文件
//        List<MultipartFile> file = ((MultipartHttpServletRequest) request).getFiles("multipart");
        if (!file.isEmpty()) {
            //上传文件路径
            String path = "";
            path = SystemConstant.DEFAULT_UPLOAD_URL;
            //获得上传文件名
            String fileName = file.getOriginalFilename();
            int lastIndexOf = fileName.lastIndexOf(".");
            UUID uuid = UUID.randomUUID();
            //获取文件的后缀名 .jpg
            String suffix = fileName.substring(lastIndexOf);
            String suffix2 = fileName.substring(lastIndexOf + 1);

            File filePath = new File(path + File.separator + uuid + suffix);
            System.out.println(filePath);
            //如果文件目录不存在，创建目录
            if (!filePath.getParentFile().exists()) {
                filePath.getParentFile().mkdirs();
            }
            //获取文件大小
            //将上传文件保存到一个目标文件中
            file.transferTo(filePath);
            String fileLength = String.valueOf(filePath.length());
            if (Integer.parseInt(fileLength) > 104857600) {
                return Result.error(500, "文件过大，请注意大小");
            }
            String fileURL = "";
            fileURL = SystemConstant.DEFAULT_PDF_SERVICE_URL + uuid + suffix;
            AttModel attModel = new AttModel();
            attModel.setName(fileName);
            attModel.setAttUrl(fileURL);
            attModel.setAdminUserId(user.getId());
            attModel.setAttType(suffix2);//文件大小
            attModel.setSize(fileLength);//文件后缀名
            String[] suffixType1Arr = SystemConstant.DEFAULT_type1.split(",");
            for (int i = 0; i < suffixType1Arr.length; i++) {
                if (suffix2.contains(suffixType1Arr[i])) {
                    attModel.setType(1);
                }
            }
            String[] suffixType2Arr = SystemConstant.DEFAULT_type2.split(",");
            for (int i = 0; i < suffixType2Arr.length; i++) {
                if (suffix2.contains(suffixType2Arr[i])) {
                    attModel.setType(2);
                }
            }
            String[] suffixType3Arr = SystemConstant.DEFAULT_type3.split(",");
            for (int i = 0; i < suffixType3Arr.length; i++) {
                if (suffix2.contains(suffixType3Arr[i])) {
                    attModel.setType(3);
                }
            }
            return Result.success(fileURL);
        } else {
            return Result.error(405, "上传失败");
        }
    }


    //可以指定字符串的某个位置是什么范围的值
    public static String getRandomString2(int length) {
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(3);
            long result = 0;
            switch (number) {
                case 0:
                    result = Math.round(Math.random() * 25 + 65);
                    sb.append(String.valueOf((char) result));
                    break;
                case 1:
                    result = Math.round(Math.random() * 25 + 97);
                    sb.append(String.valueOf((char) result));
                    break;
                case 2:
                    sb.append(String.valueOf(new Random().nextInt(10)));
                    break;
            }


        }
        return sb.toString();
    }
}
